package com.example1.hello;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;





import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class Translator {

	String _clientId="adfMSapi";
	String _clientSecret="HfRXUio5E1S/EY5SmTVeh8u6zR81gtYkkryWrXzB5is=";
	String _DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
	String _Token=null;
	Date _expires=null;
	MediaPlayer _MediaPlayer=null;
	String _speakKey=null;
	//StreamingMediaPlayer _ss=new StreamingMediaPlayer(null,null,null,null,null);
	public Translator(Context  context)
	{
		//JSONObject stock_data =new JSONObject();
		//Context  context,TextView textStreamed, ImageButton	playButton, Button	streamButton,ProgressBar	progressBar
		//_ss=new StreamingMediaPlayer(context,null,null,null,null);
	}
	
	public String lan()
	{
		String uri = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForSpeak";
		HttpClient client = new DefaultHttpClient(); 
		HttpGet getMethod = new HttpGet(uri);  
		getMethod.setHeader("Authorization", "Bearer "+getToken()); 
		String lineStr=null;
		try {
			HttpResponse response = client.execute(getMethod);
			BufferedReader in = null;  
			in = new BufferedReader(  
                    new InputStreamReader(  
                            response.getEntity().getContent()));  
 
            int size = in.read();
            lineStr = in.readLine();
            
            
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lineStr;
	}
	public String Trans(String txt ,String fromLan,String toLan)
	{
		String uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text="+URLEncoder.encode(txt)+"&from="+fromLan+"&to="+toLan; 
		HttpClient client = new DefaultHttpClient(); 
		HttpGet getMethod = new HttpGet(uri);  
		getMethod.setHeader("Authorization", "Bearer "+getToken()); 
		String lineStr=null;
		try {
			HttpResponse response = client.execute(getMethod);
			BufferedReader in;
			in = new BufferedReader(  
                    new InputStreamReader(  
                            response.getEntity().getContent()));
			lineStr = in.readLine(); 
			
			int pos = lineStr.indexOf(">");
			int end = lineStr.indexOf("</string>");
			String value = lineStr.substring(pos+1, end);
			lineStr = value;
            in.close(); 
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lineStr;
	}
	
	public void speak(String txt,String lan)
	{
	    if(_MediaPlayer==null || _speakKey==null || !_speakKey.equals(txt+","+lan))
	    {
	    	MediaPlayer mp = getspeak(txt,lan);
	    	if(mp!=null)
	    	{ 
	    	  _MediaPlayer = mp;
	    	  _speakKey=txt+","+lan;
	    	}
	    }
	    if(_MediaPlayer==null) return ;
	    if (_MediaPlayer.isPlaying()) 
	    {
	    	_MediaPlayer.stop();
	    	
	    }
	    try {
			_MediaPlayer.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    _MediaPlayer.start();
	}
	
	public void release() 
	{
		  if (_MediaPlayer != null)
		  {
		   if (_MediaPlayer.isPlaying()) 
		   {
			   _MediaPlayer.stop();
		   }
		   _MediaPlayer.release();
		   _MediaPlayer = null;
		  }
	}
	
	
	private MediaPlayer getspeak(String txt,String lan)
	{
		
		String uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?text="+URLEncoder.encode(txt)+"&language="+lan+"&format=" + URLEncoder.encode("audio/wav") + "&options=MaxQuality";
		HttpClient client = new DefaultHttpClient(); 
		HttpGet getMethod = new HttpGet(uri);  
		getMethod.setHeader("Authorization", "Bearer "+getToken()); 
        try {
			HttpResponse response = client.execute(getMethod);
			InputStream is=  response.getEntity().getContent();
			
			
			//_ss.downloadAudioIncrement(is);
			
			File temp = File.createTempFile("mediaplayertmp", "temp");
			   String tempPath = temp.getAbsolutePath();
			   FileOutputStream out = new FileOutputStream(temp);
			   //?�BufferdOutputStream?�度�?
			   BufferedOutputStream bis = new BufferedOutputStream(out);
			   byte buf[] = new byte[10240];
			   do {
			    int numread = is.read(buf);
			    if (numread <= 0)
			     break;
			    bis.write(buf, 0, numread);
			   } while (true);
			   bis.close();
			   out.close();
			   MediaPlayer mp = new MediaPlayer();
			   
			 
			   mp.setDataSource(tempPath);
			   
			  
			   temp.deleteOnExit();
			   return mp;
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
        return null;
        
        
	}
	
	private String getToken()
	{
		Calendar calendar = Calendar.getInstance();
		Date nowtime = calendar.getTime();
		if(_Token==null || _expires==null || nowtime.getTime() > _expires.getTime() )
		{
			String cd = getCredentials();
			JSONObject stock_data;
			try {
				stock_data = new JSONObject(cd);
				_Token = stock_data.getString("access_token");
				String expires_in =  stock_data.getString("expires_in");
				Calendar calendar2 = Calendar.getInstance();
				calendar2.add(Calendar.SECOND, Integer.parseInt(expires_in));
				_expires=calendar2.getTime();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
		return _Token;
	    
	}
	
	
	private String getCredentials()
	{
		
		
        //this.token = HttpPost(_DatamarketAccessUri, this.request);
        
        try {  
        	BufferedReader in = null;  
        	HttpClient client = new DefaultHttpClient(); 
            HttpPost postMethod = new HttpPost(_DatamarketAccessUri);  
            
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
            //添�?要�??��??�数    
            postParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));  
           // postParameters.add(new BasicNameValuePair("client_id", URLEncoder.encode(_clientId,"UTF-8")));  
           // postParameters.add(new BasicNameValuePair("client_secret", URLEncoder.encode(_clientSecret,"UTF-8")));
            postParameters.add(new BasicNameValuePair("client_id", _clientId));  
            postParameters.add(new BasicNameValuePair("client_secret",_clientSecret));
            postParameters.add(new BasicNameValuePair("scope", "http://api.microsofttranslator.com"));

            //实�??�UrlEncodedFormEntity对象  
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
                    postParameters);  
            
            
            postMethod.setEntity(formEntity); //将�??�填?�POST Entity�? 
        
            HttpResponse response = client.execute(postMethod); //?��?POST?��?  
            
            in = new BufferedReader(  
                    new InputStreamReader(  
                            response.getEntity().getContent()));  
 
            
            String lineStr = in.readLine(); 
            in.close(); 
            
            
            return lineStr;
            

            
                          
        } catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } 
        return null;
	}
	
/*	public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }
	private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
    {
        //Prepare OAuth request 
        WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
        webRequest.ContentLength = bytes.Length;
        using (Stream outputStream = webRequest.GetRequestStream())
        {
            outputStream.Write(bytes, 0, bytes.Length);
        }
        using (WebResponse webResponse = webRequest.GetResponse())
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            return token;
        }
    }*/
	
	
}
